//
// Created by ashCheng on 2022/11/15.
//
#include <cstdio>
#include <boost/filesystem.hpp>
#include <iostream>
#include <cstdlib>

namespace fs = boost::filesystem;

void listDirs() {
  fs::path path("/usr/local/include/node");  // random pathname
  if (!fs::is_directory(path)) return;
  std::vector<std::string> filenames;
  fs::directory_iterator end_iter;
  uint64_t ts_now = std::time(nullptr);
  std::cout << ts_now << std::endl;
  for (fs::directory_iterator iter(path); iter!=end_iter; ++iter)
  {
    if (fs::is_regular_file(iter->status()))
    {
      std::string fn = iter->path().string();
      filenames.push_back(fn);
      uint64_t ts_lw = fs::last_write_time(fs::path(fn));
      std::cout << "找到文件:" << fn << " 文件的最后一次修改时间为:" << ts_lw << std::endl;
      std::cout << "当前时间" << (ts_now > ts_lw ? "大于" : "小于") << "该时间" << std::endl;
    }
  }
}

void createAndWriteFile() {
  //目录下新建一个文件
  std::string path("./file.txt"); //in the dir build

  if (access(path.c_str(), 0) != F_OK) {
    std::string mk("touch ");
    mk += path;
    std::system(mk.c_str());
  }
  FILE *fp;
  fp=fopen(path.c_str(),"a");
  if(!fp){
    std::cout << "Failed to open file " << path << std::endl;
    exit(0);
  }
  for(int i=1; i<5; i++)
    fprintf(fp,"%s\n","what the fuck");
  fclose(fp);
}

void readExecuteCmd() {
  std::string cmd("ls .");
  FILE *fp;
  fp = popen(cmd.c_str(), "r");
  if (fp == nullptr) {
    std::cout << "------ failed to execute " << cmd;
  } else {
    bool flag = false;
    //按行读取
    char content[1024];
    int duration = 0;//单位秒
    while (fgets(content, sizeof(content) - 1, fp) != nullptr) {

      /**
       * 测试打印部分代码
       */
      std::cout << "执行命令读取:" << content;
    }
  }
}

int main() {
  listDirs();
  createAndWriteFile();
  readExecuteCmd();
  return 0;
}